const fs = require('fs');

// 读取路由写入router
const addMapping = (router, mapping) => {
    for (url in mapping) {
        if (url.startsWith('GET ')) {
            const path = url.substring(4);
            router.get(path, mapping[url]);
        } else if (url.startsWith('POST ')) {
            const path = url.substring(5);
            router.post(path, mapping[url])
        } else if (url.startsWith('PUT ')) {
            const path = url.substring(4);
            router.put(path, mapping[url]);
        } else if (url.startsWith('DELETE ')) {
            const path = url.substring(7);
            router.del(path, mapping[url]);

        } else {
            console.log(`错误的URL : ${url}`);
        }
    }
};
// 获取路由
const addRouters = router => {
    const files = fs.readdirSync(__dirname + '/modules');
    const js_files = files.filter(f => {
        return f.endsWith('.js');
    });
    for (let f of js_files) {
        let mapping = require(__dirname + '/modules/' + f);
        addMapping(router, mapping);
    };
};

module.exports = function () {
    let router = require('koa-router')();
    addRouters(router);
    return router.routes();
}